package com.bigdata.zkapi;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class ZkSimpleApi {
    private static final String conntectPath="hadoop1:2181,hadoop2:2181,hadoop3:2181";
    private static final int sessionTimeout = 2000;
    ZooKeeper zooKeeper = null;

    @Before
    public void init() throws Exception{

        zooKeeper = new ZooKeeper(conntectPath, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getType()+"----"+event.getPath());
                try {
                    zooKeeper.getChildren("/",true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /*添加节点*/
    @Test
    public void testCreateNode() throws Exception{
        /*ZooDefs.Ids.OPEN_ACL_UNSAFE：关于权限控制，表明之后对节点的任何操作都不受权限控制。
        * CreateMode：（1）PERSISTENT：持久；（2）PERSISTENT_SEQUENTIAL：持久顺序；（3）EPHEMERAL：临时；（4）EPHEMERAL_SEQUENTIAL：临时顺序。
        * */
        String node = zooKeeper.create("/eclipse","zhanghui".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
        assertEquals(node,"/eclipse");
    }

    //判断znode是否存在
    @Test
    public void testZnodeExist() throws  Exception{
        Stat stat = zooKeeper.exists("/eclipse",false);
        assertTrue(stat!=null);
    }

    // 获取子节点
    @Test
    public void testGetChild() throws Exception{
        List<String> childs =  zooKeeper.getChildren("/",true);
        for (String child: childs
             ) {
            System.out.println(child);
        }
    }
    //获取znode的数据
    @Test
    public void testGetZondeData() throws Exception{
        byte[] data =  zooKeeper.getData("/eclipse",false,null);
        System.out.println(new String(data));
    }

    //设置znode数据
    @Test
    public void testAddZondeData() throws Exception{
        zooKeeper.setData("/eclipse","我爱你张慧慧".getBytes(),-1);
        byte[] data =  zooKeeper.getData("/eclipse",false,null);
        System.out.println(new String(data));
    }
    //删除节点
    @Test
    public void testDeleteZnode() throws Exception{
        //参数2：指定要删除的版本，-1代表所有版本
        zooKeeper.delete("/zk1",-1);
    }
}
